clc; clearvars; close all;
addpath('CEC2010\')
addpath('CEC2010\datafiles\');
addpath('CEC2010\javarandom\bin\');
addpath('CEC2010\javarandom\src\');
groupInfor = load('groupInfor.mat', 'groupInfor');
groupInfor = groupInfor.groupInfor;
% evaluation = load('evaluation.mat', 'evaluation');
global initial_flag

NS = 100;   % 种群数
dim = 1000;   % 种群维度
s = size(groupInfor, 2);   % 子控件数目
upperBound = [100, 5, 32, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 100];
lowerBound = [-100, -5, -32, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -100];
bestYhistory = [];    % 保存每次迭代的最佳值

for funcNum = 4

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sampleX = lhsdesign(NS, dim) .* (upperBound(funcNum) - lowerBound(funcNum)) + lowerBound(funcNum) .* ones(NS, dim);    % 生成NS个种群,并获得其评估值
    lastSampleX = sampleX;
    sampleY = benchmark_func(sampleX, funcNum);
    [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
    lastBestY = bestY;
    bestX = sampleX(bestIndex, :);
    bestYhistory = [bestYhistory; bestY];
    evalue = 100;

    while evalue < 5 * 10 ^ 6     % 迭代50次
        for i1 = 1 : s
            group = groupInfor{i1};
            dim = size(group,2);
            NPi = dim + 10;
            Geni = dim + 5;
%             if Geni > 500
%                 Geni = 500;
%             end
            index = randperm(NS);
            subX = sampleX(index(1:NPi), group);
            [subX, subY] = JADE(subX, sampleY(index(1:NPi)), bestX, group, Geni, dim, lowerBound(funcNum), upperBound(funcNum), @(x)benchmark_func(x, funcNum));
            evalue = evalue + NPi * Geni;
            sampleX(index(1:NPi), group) = subX;
            sampleY(index(1:NPi)) = benchmark_func(sampleX(index(1:NPi), :), funcNum);   
            evalue = evalue + NPi;
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
        end
        bestYhistory = [bestYhistory; bestY];
        fprintf('evalue:%d\n', evalue);
    end
end
plot(bestYhistory);
save('bestYhistory.mat','bestYhistory');